import path from 'path';
import fs from 'fs';
import base64 from 'base-64';
import Config from '../conf';
import {
	simpleTemplate
} from '../modules';
import indexView from '../views';

async function Index(cx,next){
	cx.type='text/html';
	const htm=await fsReadFile(path.resolve(process.cwd(),'static/index.html'));
	cx.response.body=htm;
}
async function Book(cx,next){
	cx.type='text/html';
	const dirname = cx.params.book;
	if(!/\/$/.test(cx.path)) {
		cx.response.redirect('/'+dirname+'/');
		return;
	}
	const book = await cx.locServe.books.find({dirname});

	try{
		if (book.length) {	
			let reg=new RegExp('^\/{1}(?!'+dirname+')','i');
			const bookJson = JSON.parse(decodeURIComponent(base64.decode(book[0].bookjson)));
			const index = bookJson.index;
			let htm = await fsReadFile(path.join(process.cwd(),Config.upload.uploadedDir,dirname,(index||'/index.html')));
			htm=htm.replace(/(<(?:link|script).+?(?:href|src)=")([^>]+)("\s*\/?>)/ig,(a,b,c,d)=>{
				if(reg.test(c)) c='.'+c;
				return b+c+d;
			});
			cx.body=htm;
			return;
		}
	}catch(e){}
	cx.response.redirect('/404.html');
}
function fsReadFile(fpath){
	return new Promise((resolve,reject)=>{
		fs.readFile(fpath,'utf8',(err,data)=>{
			if (err) {
				reject(err);
			}else{
				resolve(data);
			}
		});
	});
}
const pageRoutes = {
	'/':Index,
	'/:book':Book,
	// just a default route type
	__setDefaultType__:'get'
}

export default pageRoutes;


